
module Uart_Tx_Module
(
	CLK_50M,RST_N,in_rx_data,tx_start_flag,tx_bps_flag,
	UART_TX,tx_bps_start
);

input				CLK_50M;					
input				RST_N;					
input 				tx_start_flag;		    //启动发送的标志, 0有效。只需要保持超过20ns
input 				tx_bps_flag;			
input		[ 7:0] 	in_rx_data;			
output 				tx_bps_start;			//发送期间保持高(1)，发送结束变为低(0)
output 				UART_TX;					

reg		[ 1:0]	detect_edge;		
wire	[ 1:0]	detect_edge_n;		
reg				negedge_reg;			
wire			negedge_reg_n;		
reg				tx_bps_start;			
reg				tx_bps_start_n;		
reg		[ 7:0] 	tx_temp_data;			
reg		[ 7:0] 	tx_temp_data_n;		
reg		[ 3:0] 	bit_cnt;				
reg		[ 3:0] 	bit_cnt_n;			
reg				UART_TX;				
reg				UART_TX_N;			

always @ (posedge CLK_50M or negedge RST_N)
begin
	if(!RST_N)								
		detect_edge	<= 2'b11;			
	else
		detect_edge <= detect_edge_n;		
end


assign detect_edge_n = {detect_edge[0], tx_start_flag};	


always @ (posedge CLK_50M or negedge RST_N)
begin
	if(!RST_N)									
		negedge_reg	<= 1'b0;				
	else
		negedge_reg <= negedge_reg_n;		
end


assign negedge_reg_n = (detect_edge == 2'b10) ? 1'b1 : 1'b0; 


always @ (posedge CLK_50M or negedge RST_N) 
begin
	if(!RST_N)									
		tx_bps_start <= 1'b0;				
	else
		tx_bps_start <= tx_bps_start_n;
end


always @ (*)
begin
	if(negedge_reg)							
		tx_bps_start_n = 1'b1;				
	else if(bit_cnt == 4'd10)			
		tx_bps_start_n = 1'b0;				
	else
		tx_bps_start_n = tx_bps_start;	
end


always @ (posedge CLK_50M or negedge RST_N) 
begin
	if(!RST_N)								
		tx_temp_data <= 1'b0;				
	else
		tx_temp_data <= tx_temp_data_n;	
end


always @ (*)
begin
	if(negedge_reg)							
		tx_temp_data_n = in_rx_data;		
	else
		tx_temp_data_n = tx_temp_data;	
end


always @ (posedge CLK_50M or negedge RST_N)
begin
	if(!RST_N)								
		bit_cnt <= 4'b0;					
	else
		bit_cnt <= bit_cnt_n;				
end


always @ (*)
begin
	if(tx_bps_flag)						
		bit_cnt_n = bit_cnt + 1'b1;		
	else if(bit_cnt == 4'd10)				
		bit_cnt_n = 1'b0;						
	else
		bit_cnt_n = bit_cnt;				
end


always @ (posedge CLK_50M or negedge RST_N)
begin
	if(!RST_N) 									
		UART_TX <= 1'b1;						
	else
		UART_TX <= UART_TX_N;			
end


always @ (*)
begin
	if(tx_bps_flag)							
		case (bit_cnt)					
			4'd0: UART_TX_N = 1'b0; 				
			4'd1: UART_TX_N = tx_temp_data[0];	
			4'd2: UART_TX_N = tx_temp_data[1];	
			4'd3: UART_TX_N = tx_temp_data[2];	
			4'd4: UART_TX_N = tx_temp_data[3];	
			4'd5: UART_TX_N = tx_temp_data[4];	
			4'd6: UART_TX_N = tx_temp_data[5];	
			4'd7: UART_TX_N = tx_temp_data[6];	
			4'd8: UART_TX_N = tx_temp_data[7];	
			4'd9: UART_TX_N = 1'b1;					
			default: UART_TX_N = 1'b1;
		endcase
	else
		UART_TX_N = UART_TX;					
end

endmodule


